<?php
$db = new Database;
$auth = Auth::getAuth('current_user');
$user_id = $auth['id'];
$company_id = $auth['company_id'];
if(isset($_POST['action'])){
    if($_POST['action']=="countRecord"){
        $countOrgChart = $db->query("SELECT * FROM tborgchart where company_id = '$company_id' and is_active = 1","numrows");
        echo $countOrgChart;
    }elseif($_POST['action']=="saveChart"){
        //FOR OBJECTS
        
        $object_id = explode(",",implode(",",$_POST['object_id']));
        $object_tops = explode(",",implode(",",$_POST['object_tops']));
        $object_lefts = explode(",",implode(",",$_POST['object_lefts']));
        $object_role = explode(",",implode(",",$_POST['object_role']));
        //FOR LINES
        $line_id = explode(",",implode(",",$_POST['line_id']));
        $master_id = explode(",",implode(",",$_POST['master_id']));
        $child_id = explode(",",implode(",",$_POST['child_id']));
        $line_tops = explode(",",implode(",",$_POST['line_tops']));
        $line_lefts = explode(",",implode(",",$_POST['line_lefts']));
        $line_heights = explode(",",implode(",",$_POST['line_heights']));
        $line_widths = explode(",",implode(",",$_POST['line_widths']));
        $line_margin_tops = explode(",",implode(",",$_POST['line_margin_tops']));
        $line_margin_lefts = explode(",",implode(",",$_POST['line_margin_lefts']));
        $line_axis = explode(",",implode(",",$_POST['line_axis']));
        $line_type = explode(",",implode(",",$_POST['line_type']));
        //FOR OTHER DETAILS
        $chartTitle = $_POST['orgChart_title'];
        $rfr = $_POST['orgChart_rfr'];
        $chartStatus = $_POST['chartStatus'];
        //OLD ACTIVE DIAGRAM
        //to get the top node of the orchart
        $getActiveOrgChart = $db->query("SELECT id FROM tborgchart where is_active = 1 and company_id='$company_id' and status=1","row");
        $queryObject = $db->query("SELECT object_id from tborgchartobjects where orgchart_id = '".$getActiveOrgChart['id']."'","array");
        $queryRows = $db->query("SELECT object_id from tborgchartobjects where orgchart_id = '".$getActiveOrgChart['id']."'","numrows");
        $count = 0;
        $countError = array();
        $object = array();
        $topNode = "";
        $sequencialOrgChart = array();
        foreach($queryObject as $data){
            $queryLines = $db->query("SELECT DISTINCT(child_id) FROM tborgchartline where orgchart_id = '".$getActiveOrgChart['id']."'","array");
            foreach($queryLines as $dataLines){
                if($dataLines['child_id']!=$data['object_id']){
                    $count++;
                }
            }
            array_push($countError,$count);
            array_push($object,$data['object_id']);
            $count = 0;
        }
        for($a=0;$a<$queryRows;$a++){
            if($countError[$a]+1==$queryRows){
                $topNode =  $object[$a];
                break;
            }
        }
        $loopRange = $db->query("select distinct(master_id) FROM tborgchartline where orgChart_id = '".$getActiveOrgChart['id']."'","numrows");
        $arrayChilds = array();
        $arrayGroups = array();
        $queryRole = $db->query("SELECT role FROM tborgchartobjects where object_id='$topNode'","row");
        array_push($sequencialOrgChart,"Master->".$queryRole['role']);
        $sequenceCounter = 1;
        for($a=0;$a<$loopRange;$a++){
            if($a==0){
                $queryLines = $db->query("SELECT DISTINCT(child_id) FROM tborgchartline where master_id = '$topNode' and orgchart_id = '".$getActiveOrgChart['id']."'","array");
                foreach($queryLines as $dataqueryLines){
                    $queryRole = $db->query("SELECT role FROM tborgchartobjects where object_id='".$dataqueryLines['child_id']."' and orgchart_id = '".$getActiveOrgChart['id']."'","row");
                    $queryMasterNode = $db->query("SELECT role FROM tborgchartobjects where object_id='$topNode' and orgchart_id = '".$getActiveOrgChart['id']."'","row");
                    //echo $queryRole['role'].",";
                    array_push($arrayChilds,$dataqueryLines['child_id']);
                    array_push($sequencialOrgChart,$queryMasterNode['role']."->".$queryRole['role']);
                }    
            }else{
                for($c=0;$c<count($arrayChilds);$c++){
                    $query = $db->query("SELECT DISTINCT(child_id) FROM tborgchartline where master_id = '$arrayChilds[$c]' and orgchart_id = '".$getActiveOrgChart['id']."'","array");
                    $sequenceCounter++;
                    foreach($query as $data){
                        $queryRole = $db->query("SELECT role FROM tborgchartobjects where object_id='".$data['child_id']."' and orgchart_id = '".$getActiveOrgChart['id']."'","row");
                        $queryMasterRole = $db->query("SELECT role FROM tborgchartobjects where object_id='".$arrayChilds[$c]."' and orgchart_id = '".$getActiveOrgChart['id']."'","row");
                        //echo $queryMasterRole['role']."->".$queryRole['role'].",";
                        array_push($arrayChilds,$data['child_id']);
                        
                        array_push($sequencialOrgChart,$queryMasterRole['role']."->".$queryRole['role']);
                        
                    }
                    //echo "\n";
                    
                }
                $arrayChilds = array();
                $arrayChilds = array();
            }
            //echo "\n";
        }
        
        //NEW ORGCHART
        //INSERT TO TEMP LINES
        for($lines=0;$lines<count($line_id);$lines++){
            if($line_type[$lines]==2){
                $tempLines = array(
                    "workflow_id"=>"0_".$company_id,
                    "master_id"=>$master_id[$lines],
                    "child_id"=>$child_id[$lines],              
                    );
                $insertTempWorkflow = $db->insert("tbtemp_lines",$tempLines);
            }
        }
        //INSERT TO TEMP OBJECT
            for($obj=0;$obj<count($object_id);$obj++){
                $tempObj = array(
                    "workflow_id"=>"0_".$company_id,
                    "object_id"=>$object_id[$obj],
                    "role"=>$object_role[$obj],
                    );
                $insertObj = $db->insert("tbtemp_obj",$tempObj);
            }
        //get master
        $queryObject = $db->query("SELECT object_id from tbtemp_obj where workflow_id = '0_$company_id'","array");
        $queryRows = $db->query("SELECT object_id from tbtemp_obj where workflow_id = '0_$company_id'","numrows");
        $count = 0;
        $countError = array();
        $object = array();
        $topNode = "";
        $sequencialOrgChartNew = array();
        foreach($queryObject as $data){
            $queryLines = $db->query("SELECT DISTINCT(child_id) FROM tbtemp_lines where workflow_id = '0_$company_id'","array");
            foreach($queryLines as $dataLines){
                if($dataLines['child_id']!=$data['object_id']){
                    $count++;
                }
            }
            array_push($countError,$count);
            array_push($object,$data['object_id']);
            $count = 0;
        }
        $countMaster = 0;
        for($a=0;$a<$queryRows;$a++){
            if($countError[$a]+1==$queryRows){
                $topNode =  $object[$a];
                $countMaster++;
            }
        }
        $loopRange = $db->query("select distinct(master_id) FROM tbtemp_lines where workflow_id = '0_$company_id'","numrows");
        $arrayChilds = array();
        $queryRole = $db->query("SELECT role FROM tbtemp_obj where object_id='$topNode' and workflow_id = '0_$company_id'","row");
        array_push($sequencialOrgChartNew,"Master->".$queryRole['role']);
        $sequenceCounter = 2;
        for($a=0;$a<$loopRange;$a++){
            if($a==0){
                $queryLines = $db->query("SELECT DISTINCT(child_id) FROM tbtemp_lines where master_id = '$topNode' and workflow_id = '0_$company_id'","array");
                foreach($queryLines as $dataqueryLines){
                    $queryRole = $db->query("SELECT role FROM tbtemp_obj where object_id='".$dataqueryLines['child_id']."' and workflow_id = '0_$company_id'","row");
                    $queryMasterNode = $db->query("SELECT role FROM tborgchartobjects where object_id='$topNode'","row");
                    //echo $queryRole['role'].",";
                    array_push($arrayChilds,$dataqueryLines['child_id']);
                    array_push($sequencialOrgChartNew,$queryMasterNode['role']."->".$queryRole['role']);
                }    
            }else{
                for($c=0;$c<count($arrayChilds);$c++){
                    $query = $db->query("SELECT DISTINCT(child_id) FROM tbtemp_lines where master_id = '$arrayChilds[$c]' and workflow_id = '0_$company_id'","array");
                    $sequenceCounter++;
                    foreach($query as $data){
                        $queryRole = $db->query("SELECT role FROM tbtemp_obj where object_id='".$data['child_id']."' and workflow_id = '0_$company_id'","row");
                        $queryMasterRole = $db->query("SELECT role FROM tbtemp_obj where object_id='".$arrayChilds[$c]."' and workflow_id = '0_$company_id'","row");
                        //echo $queryMasterRole['role']."->".$queryRole['role'].",";
                        array_push($arrayChilds,$data['child_id']);
                        array_push($sequencialOrgChartNew,$queryMasterRole['role']."->".$queryRole['role']);
                    }
                    //echo "\n";
                }
                $arrayChilds = array();
                $arrayChilds = array();
            }
            //echo "\n";
        }
        /*echo "Active Organizational Chart \n";
        print_r($sequencialOrgChart);
        echo "New Organizational Chart \n";
        print_r($sequencialOrgChartNew);
        echo "\n";*/
        $merge = array();
        //echo "---------------------------------- \n";
        //echo "Active Organizational Chart \n";
        foreach($sequencialOrgChartNew as $k => $v){
            $merge[$k] = $v;
            //
            $merge2Array = explode("->",$v);
            $merge2[$k] = $merge2Array[1];
            //echo $v . "\n";
        }
        
        //echo "---------------------------------- \n";
        //echo "\n";
        //echo "---------------------------------- \n";
        $deletedRole = array();
        $updatedRole = array();
        $validateIfUpdateOrgchart = 0;
        foreach($sequencialOrgChart as $k => $v){
            //update and delete
            if(in_array($v,$merge)==false){
                //echo $v . "\n";
                $updatedArray = explode("->",$v);
                array_push($updatedRole,$updatedArray[1]);
                $validateIfUpdateOrgchart++;
            }
            //delete
            $valueArray = explode("->",$v);
            if(in_array($valueArray[1],$merge2)==false){
                //echo $valueArray[1]."\n";
                array_push($deletedRole,$valueArray[1]);
            }
        }
        //validate add nodes
        $additionalNodes = 0;
        if(count($sequencialOrgChartNew)>count($sequencialOrgChart)){
            $additionalNodes++;
        }
        //validate if nodes do not have a role
        $validateRoles = 0;
        if(in_array("",$object_role)){
           $validateRoles++;
        }
        $updateActiveOrgChart = 0;
        //deleted nodes
        if($countMaster==1){ //if countMaster var = 1 orgchart does not have an error
            if($validateRoles==0){
                if($validateIfUpdateOrgchart>0 || $additionalNodes >0){
                    //update
                    if($chartStatus==1){
                        $COuntDeleted = 0;
                        foreach($deletedRole as $key=>$values){
                            $selectPendingRequest = $db->query("SELECT * FROM tbrequest r
                                                               LEFT JOIN tbrequest_process rp on rp.request_id = r.id
                                                               where rp.status = 0 and r.company_id = $company_id and rp.approver like '%".$values."%'","numrows");
                            if($selectPendingRequest>0){
                                $COuntDeleted++;
                            }
                        }
                        if($COuntDeleted>0){
                            echo "<+>"; //Admin want to delete node but has a pending request
                        }else{
                            $update = array(
                            "status"=>0
                            );
                            $condition = array(
                                "company_id"=>$company_id
                                );
                            $db->update("tborgchart",$update,$condition);
                            //Search the valid node to update
                            $trueNodesToUpdate = array();
                            $countUpdate = 0;
                            foreach($updatedRole as $key=>$value){
                                if(in_array($value,$deletedRole)==false){
                                    array_push($trueNodesToUpdate,$value);
                                    $countUpdate++;
                                }
                            }
                            //Reset Requests
                            if($countUpdate>0){
                                foreach($trueNodesToUpdate as $k => $value){
                                    //echo $value;
                                    $getMasterObjectID = $db->query("SELECT object_id from tborgchartobjects where role='$value'","row");
                                    $getMasterRole = $db->query("SELECT * from tborgchartobjects oo left join tborgchartline ol on oo.object_id = ol.master_id where oo.orgChart_id = '".$getActiveOrgChart['id']."' and ol.orgChart_id = '".$getActiveOrgChart['id']."' and ol.child_id = '".$getMasterObjectID['object_id']."'","row");
                                    $requestQuery = $db->query("SELECT rp.approver as past_approver,u.role_type as role_type,r.id as id, u.role as user_reques_role,oo.object_id as object_id  FROM `tbrequest` r LEFT JOIN `tbrequest_process` rp on r.id = rp.request_id LEFT JOIN tbuser u on r.user_id = u.id left join tborgchartobjects oo on oo.role=u.role where r.status=0 and oo.orgChart_id = '".$getActiveOrgChart['id']."' and rp.approver like '%".$getMasterRole['role']."%' and oo.orgChart_id = '".$getActiveOrgChart['id']."'","array");
                                    $requestRow = $db->query("SELECT rp.approver as past_approver,u.role_type as role_type,r.id as id, u.role as user_reques_role,oo.object_id as object_id  FROM `tbrequest` r LEFT JOIN `tbrequest_process` rp on r.id = rp.request_id LEFT JOIN tbuser u on r.user_id = u.id left join tborgchartobjects oo on oo.role=u.role where r.status=0 and oo.orgChart_id = '".$getActiveOrgChart['id']."' and rp.approver like '%".$getMasterRole['role']."%' and oo.orgChart_id = '".$getActiveOrgChart['id']."'","numrows");
                                    if($requestRow>0){
                                        foreach($requestQuery as $requestData){
                                            $getNewMasterRole = $db->query("SELECT * from tbtemp_obj oo left join tbtemp_lines ol on oo.object_id = ol.master_id where oo.workflow_id = '0_$company_id' and ol.workflow_id = '0_$company_id' and ol.child_id = '".$requestData['object_id']."'","row");
                                            if(roleType($requestData['role_type'])=="Head"){
                                                $approverDept = $getNewMasterRole['role'];
                                                $wf_master_id = $getNewMasterRole['object_id'];
                                            }else{
                                                $approverDept = $requestData['user_reques_role'];
                                                $wf_master_id = $requestData['object_id'];
                                            }
                                            $approverType = explode("_",$requestData['past_approver']);
                                            $newApprover = $approverType[0]."_".$approverDept;
                                            //echo $newApprover;
                                            //echo "Reset".$requestData['id']."to approver: ".$getNewMasterRole['role'].",";
                                            $deleteRequestArray = array(
                                                        "request_id"=>$requestData['id']                
                                                        );
                                            $db->delete("tbrequest_process",$deleteRequestArray);
                                            $insertRequestProcess = array(
                                                    "request_id"=>$requestData['id'],
                                                    "approver"=>$newApprover,
                                                    "wf_master_id"=>$wf_master_id,
                                                    "status"=>0
                                            );
                                            $db->insert("tbrequest_process",$insertRequestProcess);
                                            $countUpdateRequest++;
                                        }
                                    }
                                }
                                //$updateActiveOrgChart++;
                            }
                            //Update Node
                            //echo "Update Done";
                            $updateActiveOrgChart++;
                        }
                    }else{
                        $updateActiveOrgChart++;
                    }
                }else{
                    echo "<->"; //No Update Found
                }    
            }else{
                echo "error"; //error in roles input
            }
        }else{
            echo "error"; //error in orgchart creation
        }
        
        
        $deleteTemp = array(
            "workflow_id"=>"0_".$company_id
            );
        $db->delete("tbtemp_lines",$deleteTemp);
        $db->delete("tbtemp_obj",$deleteTemp);
        
        if($updateActiveOrgChart>0){
            //inserts
            $orgChartDetails = array(
                    "company_id"=>$company_id,
                    "title"=>$chartTitle,
                    "reasonForRevision"=>$rfr,
                    "date"=>"",
                    "status"=>$chartStatus,
                    "is_active"=>1
                    );
            $insertorgChartDetails = $db->insert("tborgchart",$orgChartDetails);
            for($obj=0;$obj<count($object_id);$obj++){
                $orgChartObjects = array(
                    "orgChart_id"=>$insertorgChartDetails,
                    "object_id"=>$object_id[$obj],
                    "tops"=>$object_tops[$obj],
                    "lefts"=>$object_lefts[$obj],
                    "role"=>$object_role[$obj],
                    );
                $insertorgChartObject = $db->insert("tborgchartobjects",$orgChartObjects);
            }
            for($lines=0;$lines<count($line_id);$lines++){
                $orgChartLines = array(
                    "line_id"=>$line_id[$lines],
                    "orgChart_id"=>$insertorgChartDetails,
                    "master_id"=>$master_id[$lines],
                    "child_id"=>$child_id[$lines],
                    "tops"=>$line_tops[$lines],
                    "lefts"=>$line_lefts[$lines],
                    "heights"=>$line_heights[$lines],
                    "widths"=>$line_widths[$lines],
                    "margin_tops"=>$line_margin_tops[$lines],
                    "margin_lefts"=>$line_margin_lefts[$lines],
                    "axis"=>$line_axis[$lines],
                    "line_type"=>$line_type[$lines],
                    );
                $insertorgChartLines = $db->insert("tborgchartline",$orgChartLines);
            }
            echo "Update Done";
        }else{
            //echo $updateActiveOrgChart;
        }
        
    }
}
    
?>